//
//  HNSH_CustomerToors.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/7/4.
//

#import "HNSH_CustomerToors.h"
#import "QMChatRoomViewController.h"
#import <QMLineSDK/QMLineSDK.h>
#import "QMHeader.h"

static NSString *kf_appkey = @"0c4afe50-1a19-11ee-97ca-4306070529a5";
static NSString *kf_name = @"测试test";
static NSString *kf_userId = @"123456789";

@interface HNSH_CustomerToors ()

//指示器
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
//按钮连点控制
@property (nonatomic, assign) BOOL isConnecting;
//注册成功返回值
@property (nonatomic, copy) NSDictionary *dictionary;

@end

@implementation HNSH_CustomerToors

+ (instancetype)share {
    static HNSH_CustomerToors *ad ;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        ad = [[HNSH_CustomerToors alloc]init];
    });
    return ad;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(registerSuccess:) name:CUSTOM_LOGIN_SUCCEED object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(registerFailure:) name:CUSTOM_LOGIN_ERROR_USER object:nil];
        
        //指示器
        self.indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        self.indicatorView.layer.cornerRadius = 5;
        self.indicatorView.layer.masksToBounds = YES;
        self.indicatorView.frame = CGRectMake((QM_kScreenWidth-100)/2, (QM_kScreenHeight-100)/2-64, 100, 100);
        self.indicatorView.backgroundColor = [UIColor blackColor];
        self.indicatorView.color = [UIColor whiteColor];
        self.indicatorView.alpha = 0.7;
        [kSTWindow addSubview:self.indicatorView];
    }
    return self;
}

- (void)showCustomer {
    
    [self.indicatorView startAnimating];
    
    // 按钮连点控制
    if (self.isConnecting) {
        return;
    }
    self.isConnecting = YES;
    
    /**
     accessId:  接入客服系统的密钥， 登录web客服系统（渠道设置->移动APP客服里获取）
     userName:  用户名， 区分用户， 用户名可直接在后台会话列表显示
     userId:    用户ID， 区分用户（只能使用  数字 字母(包括大小写) 下划线 短横线）
     以上3个都是必填项
     */
    
    [QMConnect switchServiceRoute:QMServiceLineTencent];
    [QMConnect registerSDKWithAppKey:kf_appkey userName:[ST_UserManager shareInstance].user.nickname userId:[ST_UserManager shareInstance].user.phone];
    
    //    [QMConnect setServerAddress:@"cc-sdk-tcp05.7moor-fs1.com" tcpPort:8008 httpPost:@"https://cc-sdk-http.7moor-fs1.com"];
}

#pragma mark - notification
- (void)registerSuccess:(NSNotification *)sender {
    QMLog(@"注册成功");
    WeakSelf(weakSelf);
    [QMConnect sdkGetWebchatScheduleConfig:^(NSDictionary *scheduleDic) {
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.dictionary = scheduleDic;
            if ([weakSelf.dictionary[@"scheduleEnable"] intValue] == 1) {
                QMLog(@"日程管理");
                [weakSelf starSchedule];
            }else{
                QMLog(@"技能组");
                [weakSelf getPeers];
            }
        });
    } failBlock:^(NSString *errorString) {
        [weakSelf getPeers];
    }];
}

- (void)registerFailure:(NSNotification *)sender {
    QMLog(@"注册失败::%@", sender.object);
    QMLineError *err = sender.object;
    if (err.errorDesc.length > 0) {
        [QMRemind showMessage:err.errorDesc];
    }
    self.isConnecting = NO;
    [self.indicatorView stopAnimating];
}

#pragma mark - 技能组选择
- (void)getPeers {
    WeakSelf(weakSelf);
    [QMConnect sdkGetPeers:^(NSArray<NSDictionary *> *peerArray) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSArray *peers = peerArray;
            weakSelf.isConnecting = NO;
            [weakSelf.indicatorView stopAnimating];
            if (peers.count == 1 && peers.count != 0) {
                [weakSelf showChatRoomViewController:[peers.firstObject objectForKey:@"id"] processType:@"" entranceId:@""];
            }else {
                [weakSelf showPeersWithAlert:peers messageStr:@"选择您咨询的类型或业务部门(对应技能组)"];
            }
        });
    } failureBlock:^(NSString *errorString) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.indicatorView stopAnimating];
            weakSelf.isConnecting = NO;
        });
    }];
}

#pragma mark - 日程管理
- (void)starSchedule {
    self.isConnecting = NO;
    [_indicatorView stopAnimating];
    if ([self.dictionary[@"scheduleId"] isEqual: @""] || [self.dictionary[@"processId"] isEqual: @""] || [self.dictionary objectForKey:@"entranceNode"] == nil || [self.dictionary objectForKey:@"leavemsgNodes"] == nil) {
        [QMRemind showMessage:@"对不起，由于在线咨询配置错误，暂时无法进行咨询"];
    }else{
        NSDictionary *entranceNode = self.dictionary[@"entranceNode"];
        NSArray *entrances = entranceNode[@"entrances"];
        if (entrances.count == 1 && entrances.count != 0) {
            [self showChatRoomViewController:[entrances.firstObject objectForKey:@"processTo"] processType:[entrances.firstObject objectForKey:@"processType"] entranceId:[entrances.firstObject objectForKey:@"_id"]];
        }else{
            [self showPeersWithAlert:entrances messageStr:@"选择您咨询的日程管理类型"];
        }
    }
}

- (void)showPeersWithAlert: (NSArray *)peers messageStr: (NSString *)message {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"选择您咨询的类型或业务部门(对应技能组)" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        self.isConnecting = NO;
    }];
    [alertController addAction:cancelAction];
    for (NSDictionary *index in peers) {
        UIAlertAction *surelAction = [UIAlertAction actionWithTitle:[index objectForKey:@"name"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([self.dictionary[@"scheduleEnable"] integerValue] == 1) {
                [self showChatRoomViewController:[index objectForKey:@"processTo"] processType:[index objectForKey:@"processType"] entranceId:[index objectForKey:@"_id"]];
            }else{
                [self showChatRoomViewController:[index objectForKey:@"id"] processType:@"" entranceId:@""];
            }
        }];
        [alertController addAction:surelAction];
    }
    [[UIViewControllerHelper findCurrentShowingViewController] presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 跳转聊天界面
- (void)showChatRoomViewController:(NSString *)peerId processType:(NSString *)processType entranceId:(NSString *)entranceId {
    if (!peerId.length) {
        [QMRemind showMessage:@"peerId不能为空"];
        return;
    }
    QMChatRoomViewController *chatRoomViewController = [[QMChatRoomViewController alloc] init];
    chatRoomViewController.peerId = peerId;
    chatRoomViewController.userName = @"";
    chatRoomViewController.isPush = NO;
    chatRoomViewController.avaterStr = @"";
    chatRoomViewController.darkStyle = QMDarkStyleDefault;
    if ([self.dictionary[@"scheduleEnable"] intValue] == 1) {
        if (!processType.length && !entranceId.length) {
            [QMRemind showMessage:@"processType和entranceId为必传参数"];
            return;
        }
        chatRoomViewController.isOpenSchedule = true;
        chatRoomViewController.scheduleId = self.dictionary[@"scheduleId"];
        chatRoomViewController.processId = self.dictionary[@"processId"];
        chatRoomViewController.currentNodeId = peerId;
        chatRoomViewController.processType = processType;
        chatRoomViewController.entranceId = entranceId;
    }else{
        chatRoomViewController.isOpenSchedule = false;
    }
    [[UIViewControllerHelper findCurrentShowingViewController].navigationController pushViewController:chatRoomViewController animated:YES];
}


@end
